package org.example.core.template;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.*;

/**
 * 占位符模板工具, 用于快速根据模板创建字符串
 */
public class PlaceholderTemplate {

    @Getter
    @RequiredArgsConstructor
    public static class TextFragment {
        public static int PLAIN = 0;
        public static int PLACEHOLDER = 1;

        private final int type;
        private final String content;
    }

    private final List<TextFragment> textFragments;

    private PlaceholderTemplate(List<TextFragment> textFragments) {
        this.textFragments = textFragments instanceof RandomAccess
                ? textFragments
                : new ArrayList<>(textFragments);
    }

    public String generate(Map<String, Object> params) {
        if (params == null) {
            params = Collections.emptyMap();
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < textFragments.size(); i++) {
            TextFragment textFragment = textFragments.get(i);

            if (textFragment.getType() == TextFragment.PLAIN) {
                builder.append(textFragment.getContent());
            } else if (textFragment.getType() == TextFragment.PLACEHOLDER) {
                Object value = params.get(textFragment.getContent());
                builder.append(value == null ? "" : value.toString());
            }
        }
        return builder.toString();
    }

    public static PlaceholderTemplate parse(String template, char prefix, char suffix) {
        final int PLAIN = TextFragment.PLAIN;
        final int PLACEHOLDER = TextFragment.PLACEHOLDER;

        StringBuilder builder = new StringBuilder();
        List<TextFragment> textFragments = new ArrayList<>();
        int type = PLAIN;
        for (char c : template.toCharArray()) {
            if (c == prefix && type != PLACEHOLDER) {
                type = PLACEHOLDER;
                if (!builder.isEmpty()) {
                    textFragments.add(new TextFragment(PLAIN, builder.toString()));
                    builder.delete(0, builder.length());
                }
            } else if (c == suffix && type == PLACEHOLDER) {
                type = PLAIN;
                if (!builder.isEmpty()) {
                    textFragments.add(new TextFragment(PLACEHOLDER, builder.toString()));
                    builder.delete(0, builder.length());
                }
            } else {
                builder.append(c);
            }
        }

        if (!builder.isEmpty()) {
            textFragments.add(new TextFragment(TextFragment.PLAIN, builder.toString()));
        }

        return new PlaceholderTemplate(textFragments);
    }
}
